package com.hulk.dryad.web.initializer;

import com.hulk.dryad.common.component.R;
import com.hulk.dryad.common.constant.enums.BEC;
import com.hulk.dryad.common.exception.BaseRteException;
import com.hulk.dryad.common.util.JacksonUtil;
import com.hulk.dryad.common.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hulk
 */
@Slf4j
@Configuration
public class DryadExceptionHandler implements HandlerExceptionResolver {

    @Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
										 Object handler, Exception ex) {

        if (ex instanceof BaseRteException) {
          R r =  R.failed(((BaseRteException) ex).getBec());
          WebUtils.renderJson(response, JacksonUtil.toJson(r),MediaType.TEXT_HTML_VALUE);

        } else {
            R r =   R.failed(BEC.E_9999.getErrCode(),BEC.E_9999.getErrDesc()+": ["+ex.getMessage()+"]");
            WebUtils.renderJson(response,JacksonUtil.toJson(r),MediaType.TEXT_HTML_VALUE);
        }

        return null;
    }


}